<?php
namespace Admin\Controller;
use Think\Controller;
class ImgController extends Controller {
	//展示
	public function index(){
		$img = M("Img");
		// if($_GET['link'])
		// $count = $img->count();
		// $Page = new \Think\Page($count,5);
		$imgs = $img->field('id,profile,link')->order('id asc')->select();
		// $this->assign('page',$page->show());
		$this->assign('imgs',$imgs);
		$this->display();
	}
	//添加
	public function add(){
		if($_POST['sub']){
			if(!(empty($_POST['link']))){
				$img = M("img");
				$_POST['link']=$_POST['link'];
				$_POST['profile']=$this->upload();
				if($img->create()){
					if($img->add()){
						$this->redirect("Img/index");
					}else{
						$this->error("添加失败！");
					}
				}
			}
		}
		$this->display();
	}

	//修改
	public function mod(){
		$img = M('img');
		$id = $_GET['id'];
		$data = $img->find($id);

		if($_POST['sub']){

			if(!empty($_POST['link'])){

				// $_POST['profile']=$this->upload();
				if($_POST['link']){

					$_POST['link']=$_POST['link'];

				}else{
					unset($_POST['link']);
				}
					// var_dump($id);exit;
				if($img->create()){
					if($img->save()){
						$this->redirect("Img/index");
					}else{
						$this->error("修改失败！");
					}
				}
			}
		}

		$this->assign('img',$data);
		$this->display();
	}
	//删除
	public function del(){
		$img = M("img");
		$id = I('id');
		$map['id']=array("IN",$id);
		if($img->where($map)->delete($id)){
			$this->redirect("Img/index");
		}else{
			$this->error("删除失败！");
		}
	}
	//图片上传
	private function upload(){
		$config = array(
			"maxSize"=>10240000,
			"exts"   =>array("jpeg","png","gif","jpg"),
			"rootPath"=>"./Public/Upload/"
			);
		$upload = new \Think\Upload($config);
		$info = $upload->uploadOne($_FILES['profile']);
		// var_dump($info);
		if($info){
			$filePath = $info['savepath'].$info['savename'];
			return $filePath;
		}else{
			$this->error($upload->getError());
		}
	}
}